// 源插件
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DateDiff, FormatnumberZero, Mover, NumberDivide } from '@/function.js';
// 视图插件
import StandardTable from '@/components/StandardTable';
import Loading from '@/components/Loading/Loading';
import { Button, Form, Input, Modal, notification, Select } from 'antd';
// 外部组件
import styles from './All.less';
// css OR less预编译器

// 图片

// 算式

const EditableContext = React.createContext();
const SelectOption = Select.Option;

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      if (values.delflag) {
        values.delflag = parseInt(e);
      }
      if (values.etftype) {
        values.etftype = parseInt(e);
      }
      handleSave({ ...record, ...values });
    });
  };

  noSaveOut = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      // handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    let nullFlag = false;
    if (
      children[2].props.children === null ||
      children[2].props.children === '' ||
      typeof children[2].props.children === 'undefined'
    ) {
      nullFlag = true;
    }
    return editing ? (
      dataIndex === 'etftype' ? (
        <Form.Item style={{ margin: 0 }}>
          {form.getFieldDecorator(dataIndex, {
            rules: [
              /* {
           required: true,
           message: `${title} is required.`,
         }, */
            ],
            initialValue: record[dataIndex].toString(),
          })(
            <Select
              ref={node => (this.input = node)}
              style={{ width: '80%' }}
              onSelect={this.save}
              onBlur={this.noSaveOut}
            >
              <SelectOption value="1">ETF</SelectOption>
              <SelectOption value="0">龙头股</SelectOption>
            </Select>
          )}
        </Form.Item>
      ) : dataIndex === 'delflag' ? (
        <Form.Item style={{ margin: 0 }}>
          {form.getFieldDecorator(dataIndex, {
            rules: [
              /* {
           required: true,
           message: `${title} is required.`,
         }, */
            ],
            initialValue: record[dataIndex].toString(),
          })(
            <Select
              ref={node => (this.input = node)}
              style={{ width: '80%' }}
              onSelect={this.save}
              onBlur={this.noSaveOut}
            >
              <SelectOption value="0">属于</SelectOption>
              <SelectOption value="1">不属于</SelectOption>
              <SelectOption value="2">未标记</SelectOption>
            </Select>
          )}
        </Form.Item>
      ) : (
        <Form.Item style={{ margin: 0 }}>
          {form.getFieldDecorator(dataIndex, {
            rules: [
              /* {
               required: true,
               message: `${title} is required.`,
             }, */
            ],
            initialValue: record[dataIndex],
          })(
            <Input
              ref={node => (this.input = node)}
              onPressEnter={this.save}
              onBlur={this.noSaveOut}
            />
          )}
        </Form.Item>
      )
    ) : (
      <div
        className={styles.editableCellValueWrap}
        style={{ padding: nullFlag ? '5px 12px' : '' }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

/**
 *  Created by xjc on 2019/5/15
 *  Describe:数据连接
 */

@connect(({ fu, loading }) => ({
  fu,
  loading: loading.models.fuRule,
}))
@Form.create()
class NewTwoFormModal extends PureComponent {
  componentWillMount() {}

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
  };

  columns = [];

  getColumns() {
    const {
      fu: { stocksFilters },
    } = this.props;
    let columns = [
      {
        title: '股票',
        dataIndex: 'stock',
        width: 100,
        align: 'center',
      },
      {
        title: '股数',
        dataIndex: 'stocknumber',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
        editable: true,
      },
      {
        title: '均价',
        dataIndex: 'avgprice',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{NumberDivide(value)}</span>;
        },
        editable: true,
      },
      {
        title: '类型',
        dataIndex: 'etftype',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{value === 1 ? 'ETF' : '龙头股'}</span>;
        },
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'type',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{value === 1 ? '买入' : '卖出'}</span>;
        },
      },
      {
        title: '是否属于',
        dataIndex: 'delflag',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{value === 0 ? '属于' : value === 1 ? '不属于' : '未标记'}</span>;
        },
        editable: true,
      },
      {
        title: '交易日期',
        dataIndex: 'date',
        align: 'center',
        width: 110,
        render: (value, row, index) => {
          return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
        },
        editable: true,
      },
    ];

    columns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return columns;
  }

  handleSave = row => {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'fu/UpdateLastTrade',
      payload: row,
      callback: res => {
        /* 导入列表数据 */
        dispatch({
          type: 'fu/GetUBSNewTwoPositionModal',
          payload: {},
          callback: res => {},
        });
      },
    });
  };

  cancelHandle() {
    this.props.closeVisbile();
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
    });
  };

  Insert() {
    const that = this;
    const key = `open${Date.now()}`;
    const { dispatch } = that.props;
    const btn = (
      <Button
        type="primary"
        size="small"
        onClick={() => {
          notification.close(key);
          dispatch({
            type: 'fu/Insert',
            callback: res => {
              /* 导入列表数据 */
              that.props.closeVisbile();
            },
          });
        }}
      >
        确定
      </Button>
    );
    notification.open({
      message: 'Notification Title',
      description: '是否开始生成',
      btn,
      key,
      onClose: close,
    });
  }

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:视图
   */

  render() {
    const {
      Visible,
      fu: { newTwoPositionModal },
    } = this.props;
    const { listLoading, selectedRows, record, StocksDetailVisible, OptionVisible } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    if (this.columns.length === 0 && newTwoPositionModal.code === 0) {
      this.columns = this.getColumns();
    }
    return (
      <Modal
        width="80%"
        destroyOnClose
        title="标记股票池"
        visible={Visible}
        centered
        onOk={this.Insert.bind(this)}
        onCancel={this.cancelHandle.bind(this)}
      >
        {newTwoPositionModal.code === 0 ? (
          <Loading />
        ) : (
          <StandardTable
            components={components}
            bordered
            selectedRows={selectedRows}
            loading={listLoading}
            data={newTwoPositionModal}
            columns={this.columns}
            style={{ tableLayout: 'fixed' }}
            className={styles.TableLayout}
            pagination={false}
            onChange={this.handleStandardTableChange}
          />
        )}
      </Modal>
    );
  }

  componentDidMount() {}

  componentWillUnmount() {}
}

export default NewTwoFormModal;
